<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="单据编号" prop="vBillNo">
        <el-input
          v-model="queryParams.vBillNo"
          placeholder="请输入单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="执行日期">
        <el-date-picker
          v-model="daterangeDExecute"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="项目编号" prop="vProjectNo">
        <el-input
          v-model="queryParams.vProjectNo"
          placeholder="请输入项目编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请人" prop="applyBy">
        <el-input
          v-model="queryParams.applyBy"
          placeholder="请输入申请人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="billList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单据编号" align="center" prop="vBillNo" />

      <el-table-column
        label="执行日期"
        align="center"
        prop="dExecute"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dExecute, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目编号" align="center" prop="vProjectNo" />
      <el-table-column label="申请人" align="center" prop="applyBy" />
      <el-table-column label="经办人" align="center" prop="oprBy" />
      <el-table-column label="单据状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.inv_outbill_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.status == '4'"
            >详情</el-button
          >

          <el-button
            size="mini"
            type="text"
            @click="handlePrint(scope.row)"
            v-if="scope.row.status == '1'"
            >打印出库单</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改出库单对话框 -->
    <el-drawer
      :title="title"
      :visible.sync="open"
      size="70%"
      ref="drawer"
      append-to-body
    >
      <div class="drawer-container">
        <div class="xin-main">
          <div class="xin-content" style="height: 90%">
            <el-form
              ref="form"
              :model="form"
              :rules="rules"
              label-width="120px"
            >
              <el-row>
                <el-col :span="8">
                  <el-form-item label="单据编号" prop="vBillNo">
                    <el-input
                      v-model="form.vBillNo"
                      placeholder="请输入单据编号"
                      disabled="true"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="执行日期" prop="dExecute">
                    <el-date-picker
                      clearable
                      v-model="form.dExecute"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="请选择执行日期"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入备注" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="项目编号" prop="vProjectNo">
                    <el-input
                      v-model="form.vProjectNo"
                      placeholder="请输入项目编号"
                      disabled="true"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="领料人" prop="applyBy">
                    <el-input
                      v-model="form.applyBy"
                      placeholder="请输入领料人"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="经办人" prop="oprBy">
                    <el-input v-model="form.oprBy" placeholder="请输入经办人" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-divider content-position="left"></el-divider>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleTableAdd"
                  >新增</el-button
                >
              </el-col>
            </el-row>
            <el-table :data="executeList" min-height="450px" border>
              <el-table-column
                label="项目编号"
                align="center"
                prop="vProjectNo"
              />
              <el-table-column label="采购单号" align="center" prop="vBuyNo" />
              <el-table-column
                label="物料名称"
                align="center"
                prop="vSpaName"
              />
              <el-table-column
                label="规格型号"
                align="center"
                prop="vSpaModel"
              />
              <el-table-column label="品牌" align="center" prop="vSpaBrand" />
              <el-table-column label="数量" align="center" prop="nQty">
                <!-- <template slot-scope="scope">
                  <el-input
                    size="small"
                    v-model="scope.row.nQty"
                    @change="handleEdit(scope.$index, scope.row)"
                    disabled="true"
                  ></el-input>
                </template> -->
              </el-table-column>
              <!-- <el-table-column label="仓库" align="center" prop="vWhName" />
              <el-table-column label="库区" align="center" prop="vAreaName" /> -->
              <el-table-column
                label="库位"
                align="center"
                prop="vLocationName"
              />
              <!-- <el-table-column prop="vWHId" label="仓库" align="center">
                <template slot-scope="scope">
                  <el-select
                    size="small"
                    clearable
                    v-model="scope.row.vWHId"
                    @change="handleWHEdit(scope.row)"
                  >
                    <el-option
                      v-for="dict in whList"
                      :key="dict.id"
                      :label="dict.vWHName"
                      :value="dict.id"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="vAreaId" label="库区" align="center">
                <template slot-scope="scope">
                  <el-select
                    size="small"
                    v-model="scope.row.vAreaId"
                    clearable
                    @change="handleAreaEdit(scope.row)"
                  >
                    <el-option
                      v-for="dict in areaList"
                      :key="dict.id"
                      :label="dict.vWHName"
                      :value="dict.id"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="vLocationId" label="库位" align="center">
                <template slot-scope="scope">
                  <el-select
                    size="small"
                    v-model="scope.row.vLocationId"
                    clearable
                    @change="handleLocaltionEdit(scope.row)"
                  >
                    <el-option
                      v-for="dict in localtionList"
                      :key="dict.id"
                      :label="dict.vWHName"
                      :value="dict.id"
                    />
                  </el-select>
                </template>
              </el-table-column> -->
            </el-table>
            <div
              class="xin-footer"
              style="position: fixed; bottom: 5px; right: 10px"
            >
              <!-- <el-button type="primary" @click="submitForm">确 定</el-button> -->
              <el-button type="primary" @click="executeOut">执行出库</el-button>
              <!-- <el-button type="primary" @click="handleUpdateStatus('4')"
                >通 过</el-button
              >
              <el-button type="primary" @click="handleUpdateStatus('3')"
                >驳 回</el-button
              > -->
              <el-button @click="cancelDrawer">取消</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- <el-dialog
      title="详情"
      :visible.sync="addOpen"
      v-if="addOpen"
      width="50%"
      append-to-body
    >
      <add :existData="executeList" @close="getAddReturn" />
    </el-dialog> -->
    <el-dialog
      title="打印出库单"
      :visible.sync="printOpen"
      width="50%"
      append-to-body
    >
      <printOut :products="currentPrintInfo" />
    </el-dialog>
  </div>
</template>

<script>
import {
  listBill,
  delBill,
  addBill,
  updateBill,
  getInfo,
  delItem,
  checkInvQty,
  executeOut,
  viewCKBillById,
  updateBillStatus,
} from "@/api/inv/inv0005";
import printOut from "./printOutNew";
// import add from "./add";
export default {
  name: "inv000502",
  dicts: ["inv_iotpye", "inv_bill_type", "inv_outbill_status"],
  components: { printOut },
  data() {
    return {
      printOpen: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出库单表格数据
      billList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 经办人时间范围
      daterangeDExecute: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        vBillNo: null,
        iotype: null,
        vType: null,
        vCorBillNo: null,
        vContractNo: null,
        dExecute: null,
        vProjectNo: null,
        applyBy: null,
        oprBy: null,
        statusList: ["1", "4"],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      addOpen: false,
      executeList: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询出库单列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeDExecute && "" != this.daterangeDExecute) {
        this.queryParams.params["beginDExecute"] = this.daterangeDExecute[0];
        this.queryParams.params["endDExecute"] = this.daterangeDExecute[1];
      }
      listBill(this.queryParams).then((response) => {
        this.billList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        vBillNo: null,
        iotype: null,
        vType: null,
        vCorBillNo: null,
        vContractNo: null,
        dExecute: this.getCurrentDate(),
        createBy: this.$store.state.user.name,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        vProjectNo: null,
        applyBy: null,
        oprBy: this.$store.state.user.name,
      };
      this.resetForm("form");
      this.executeList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeDExecute = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加出库单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getInfo(row).then((response) => {
        this.form = response.data.invOutboundBill;
        this.executeList = response.data.invOutboundBillItemList;
        this.open = true;
        this.title = "修改出库单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateBill({
              invOutboundBill: this.form,
              invOutboundBillItemList: this.executeList,
            }).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBill({
              invOutboundBill: this.form,
              invOutboundBillItemList: this.executeList,
            }).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除出库单编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBill(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/bill/export",
        {
          ...this.queryParams,
        },
        `bill_${new Date().getTime()}.xlsx`
      );
    },
    handleTableAdd() {
      this.addOpen = true;
    },
    executeOut() {
      executeOut({
        invOutboundBill: this.form,
        invOutboundBillItemList: this.executeList,
      }).then((response) => {
        if (response.code == "200") {
          this.$modal.msgSuccess("操作成功");
          this.open = false;
          this.getList();
        }
      });
    },
    cancelDrawer() {
      this.open = false;
    },
    getAddReturn(type, data) {
      this.executeList = data;
      this.addOpen = false;
    },
    itemDelete(index, row) {
      debugger;
      var _this = this;
      this.$modal
        .confirm("是否确认删除该条数据项？")
        .then(function () {
          debugger;
          if (
            row.id === "" ||
            row.id === null ||
            row.id === undefined ||
            row.id === 0
          ) {
            _this.executeList.splice(index, 1);
            console.log(_this.executeList);
          } else {
            delItem(row).then((response) => {
              _this.executeList.splice(index, 1);
              console.log(_this.executeList);
            });
            console.log("$$$$$$$$$$$$$$$");
            console.log(_this.executeList);
          }
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    handleEdit(index, row) {
      checkInvQty(row).then((response) => {});
    },
    handlePrint(row) {
      viewCKBillById(row).then((response) => {
        if (response.code == "200") {
          console.log(response);
          this.currentPrintInfo = response.data;
          this.printOpen = true;
        }
      });
    },

    vProjectNoChange(value) {},

    getCurrentDate() {
      const date = new Date();
      // 格式化日期为YYYY-MM-DD形式
      let year = date.getFullYear().toString();
      let month = (date.getMonth() + 1).toString().padStart(2, "0");
      let day = date.getDate().toString().padStart(2, "0");
      // 更新currentDate变量值
      let currentDate = `${year}-${month}-${day}`;
      return currentDate;
    },
    handleUpdateStatus(status) {
      var _this = this;
      //如果是驳回，需要在备注填写驳回原因
      if (status == "3") {
        let str = _this.form.remark;
        if (!str || str == "undefined" || str == "null") {
          this.$modal.msgError("请在备注填写驳回原因");
          return;
        }
      }
      this.$modal
        .confirm("是否确认提交该条数据项？")
        .then(function () {
          console.log("咋不好使呢");
          _this.form.status = status;
          return updateBillStatus(_this.form);
        })
        .then(() => {
          this.open = false;
          this.$modal.msgSuccess("操作成功");
          this.getList();
        })
        .catch(() => {});
    },
  },
};
</script>
